﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuanLyNhaSach.BusinessLogicLayer
{
    public enum DIEU_KIEN_NHAP
    {
        OK, KHONG_THOA_TON, KHONG_THOA_NHAP_TOI_THIEU
    }
    public class PhieuNhapBLL
    {
        DataAccessLayer.PhieuNhapDAO pn = new DataAccessLayer.PhieuNhapDAO();
        public DataTable LayTatCa()
        {
            return null;
        }
        public DataTable LayTheoThang(string dataTime)
        {
            return pn.LayTheoThang(dataTime);
        }

        private int DemChuSo(int number)
        {
            return number < 10 ? 1 : 1 + DemChuSo(number / 10);
        }

        public string TaoMaPhieuNhap()
        {
            DataTable dt = pn.LayDanhSach();
            int next = dt.Rows.Count + 1;
            if (next >= 1000) throw new Exception("Het khong gian luu phieu nhap");
            int c = DemChuSo(next);
            string result = "N";
            for (int i = 0; i < (4 - c); i++)
            {
                result += "0";
            }
            result += next;
            return result;
        }

        public DIEU_KIEN_NHAP KiemTraDieuKienNhap(string ma, string soluong)
        {
            BusinessLogicLayer.QuanLyQuyDinhBLL qd = new QuanLyQuyDinhBLL();
            BusinessLogicLayer.QuanLySachBLL qls = new QuanLySachBLL();
            DataTable data = qd.LayQuyDinh();
            int luongTonNhap = int.Parse(data.Rows[0]["LuongTonNhap"].ToString());
            int luongNhapToiThieu = int.Parse(data.Rows[0]["LuongNhapToiThieu"].ToString());
            int luong_ton = int.Parse(qls.XemThongTinSach(ma).Rows[0]["SoLuong"].ToString());
            int so_luong = int.Parse(soluong);
            if (so_luong < luongNhapToiThieu) return DIEU_KIEN_NHAP.KHONG_THOA_NHAP_TOI_THIEU;
            if (luong_ton >  300) return DIEU_KIEN_NHAP.KHONG_THOA_TON;
            return DIEU_KIEN_NHAP.OK;
        }

        public void ThemPhieuNhap(string ma, string date)
        {
            pn.ThemPhieuNhap(ma, date);
        }

        public void ThemChiTiet(string maPN, string maSach, string soLuong, string donGia)
        {
            BusinessLogicLayer.QuanLySachBLL qls = new QuanLySachBLL();            
            pn.ThemCTN(maPN, maSach, soLuong, donGia);
            qls.CapNhatSL(maSach, soLuong);
      
        }
    }
}
